import { Input, Output, EventEmitter, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { mergeDeepRight, pick, has } from 'ramda';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { Control } from 'src/app/admin/dashboard/dashboard-model';


export abstract class BasePanel implements OnDestroy {

  destroy$ = new Subject();

  @Output() changeControl = new EventEmitter<Control>();

  @Input() set control(control: Control) {
    this._control = control;
  }
  
  _control: Control;

  formGroup: FormGroup;

  constructor(
    public formBuilder: FormBuilder,
  ) { }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  formGroupChangeValue() {
    this.formGroup.valueChanges.pipe(
      takeUntil(this.destroy$)
    ).subscribe(value => {
      this.changeControl.emit(mergeDeepRight(this._control, value));
    })
  }

  patchValue(propertys: string[]) {
    let value: any = pick(propertys, this._control);

    if (has('name', value)) {
      value.options = JSON.stringify(value.options);
    }

    this.formGroup = this.formBuilder.group(value);
  }
}